package com.tfjybj.itoo.exam.provider.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dmsdbj.itoo.tool.base.service.impl.BaseServicePlusImpl;
import com.dmsdbj.itoo.tool.business.ItooResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tfjybj.itoo.exam.entity.AssessmentAdviceEntity;
import com.tfjybj.itoo.exam.model.AssessmentAdviceModel;
import com.tfjybj.itoo.exam.model.EvaluationPaperDetailModel;
import com.tfjybj.itoo.exam.model.EvaluationRecordModel;
import com.tfjybj.itoo.exam.model.QuestionNaireAllInfoModel;
import com.tfjybj.itoo.exam.provider.dao.AssessmentAdviceDao;
import com.tfjybj.itoo.exam.provider.service.AssessmentAdviceService;
import com.tfjybj.itoo.exam.provider.service.EvaluationPaperService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * TrAssessmentAdviceService接口实现类
 * ${base}表
 *
 * @author 杨江涛
 * @version 2.0.0
 * @since 2.0.0 2018-12-18 18:19:48
 */
@Service("trAssessmentAdviceService")
@Slf4j
public class AssessmentAdviceServiceImpl extends BaseServicePlusImpl<AssessmentAdviceDao, AssessmentAdviceEntity> implements AssessmentAdviceService {
    private static final String QUESTIONNAIRE_REDIS_INFO = "QUESTIONNAIRE_REDIS_INFO";
	//region 模板生成

    @Resource
    private AssessmentAdviceService assessmentAdviceService;

    @Resource
    private AssessmentAdviceDao assessmentAdviceDao;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private EvaluationPaperService evaluationPaperService;

    //endregion

    /* **********************************以下为非模板生成的内容********************************* */

    /**
     * 提交或更新问卷简答题
     * @param assessmentAdviceEntity 问卷建议实体
     * @return 是否添加成功
     * @author 杨晓慧
     * @Date 2018年12月27日08:39:44
     */
    @Override
    public ItooResult insertOrUpdateAssessmentAdvice(AssessmentAdviceEntity assessmentAdviceEntity) {

        String paperId= assessmentAdviceEntity.getPaperId();
        String studentId= assessmentAdviceEntity.getStudentId();
        String courseId= assessmentAdviceEntity.getCourseId();
        String evaluationMainId= assessmentAdviceEntity.getQuestionMainId();
        String schoolYear= assessmentAdviceEntity.getSchoolYear();
        List<AssessmentAdviceEntity> existRecord = isExistRecord(paperId,courseId, studentId, evaluationMainId, schoolYear);

        boolean exist = existRecord.size() > 0;
        if (exist) {
          //已存在存在答题记录，更新答题记录
            assessmentAdviceEntity.setId(existRecord.get(0).getId());
          final boolean update = assessmentAdviceService.updateById(assessmentAdviceEntity);
            if (update) {
                return ItooResult.build(ItooResult.SUCCESS, "更新答题记录成功！");
            }else{
                log.warn("课程问卷-更新简答题答题记录失败，答题记录-{}", assessmentAdviceEntity);
                return ItooResult.build(ItooResult.FAIL, "更新答题记录失败！");
            }
        }else{
            //不存在答题记录，添加答题记录
            final boolean save = assessmentAdviceService.save(assessmentAdviceEntity);
            if (save) {
                return ItooResult.build(ItooResult.SUCCESS, "添加答题记录成功！");
            }else{
                log.warn("课程问卷-添加简答题答题记录失败，答题记录-{}", assessmentAdviceEntity);
                return ItooResult.build(ItooResult.FAIL, "添加答题记录失败！");
            }
        }
    }




    /**
     * 返回题目的答题记录是否存在
     *
     * @param paperId          问卷id
     * @param studentId        学生id
     * @param evaluationMainId 问卷题干id
     * @author 杨晓慧
     * @Date 2018年12月27日08:39:44
     * @return 是否存在
     */
    public List<AssessmentAdviceEntity> isExistRecord(String paperId, String courseId, String studentId, String evaluationMainId, String schoolYear ) {

        QueryWrapper<AssessmentAdviceEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("paper_id", paperId);
        queryWrapper.eq("course_id", courseId);
        queryWrapper.eq("question_main_id", evaluationMainId);
        queryWrapper.eq("student_id", studentId);
        queryWrapper.eq("school_year", schoolYear);

        List<AssessmentAdviceEntity> list = assessmentAdviceService.list(queryWrapper);
        return list;
    }

    /**
     * 根据问题id和课程id题干id查询该题干下的学生作答记录
     * @param paperId  问卷id
     * @param questionMainId  题干id
     * @param courseId  课程id
     * @param schoolYear 学年学期
     * @return 建议列表
     * @author 杨晓慧
     * @Date 2018年12月27日08:39:44
     */
    @Override
    public ItooResult queryAdviceDetailByPaperId(String paperId,String questionMainId, String courseId, String schoolYear,Integer pageNo,Integer pageSize) {
        if (StringUtils.isEmpty(paperId)) {
            log.warn("课程问卷id为空，coursedId{},schoolYear{},questionMainId{}",courseId,schoolYear,questionMainId);
            return ItooResult.build(ItooResult.FAIL,"课程id问卷为空！");
        }
        if (StringUtils.isEmpty(questionMainId)) {
            log.warn("课程问卷题干id为空，coursedId{},schoolYear{},paperId{}",courseId,schoolYear,paperId);
            return ItooResult.build(ItooResult.FAIL,"课程问卷题干id为空！");
        }
        if (StringUtils.isEmpty(courseId)) {
            log.warn("课程问卷id为空，paperId{},schoolYear{},questionMainId{}",paperId,schoolYear,questionMainId);
            return ItooResult.build(ItooResult.FAIL,"课程id为空！");
        }
        if (StringUtils.isEmpty(schoolYear)) {
            log.warn("学年学期为空，paperId{},courseId{},questionMainId{}",paperId,courseId,questionMainId);
            return ItooResult.build(ItooResult.FAIL,"问卷学年学期为空！");
        }
        PageHelper.startPage(pageNo, pageSize);
        PageInfo<AssessmentAdviceModel> trAssessmentAdviceModelPageInfo = new PageInfo<>(assessmentAdviceDao.queryAdviceDetailByPaperId(paperId, questionMainId, courseId, schoolYear));
        return ItooResult.build(ItooResult.SUCCESS, "查询课程问卷简答题学生作答记录成功!", trAssessmentAdviceModelPageInfo);

    }


    /**
     * 根据问题id和课程id查询简答题题干
     * @param paperId  问卷id
     * @param courseId  课程id
     * @param schoolYear 学年学期
     * @return 简答题题干
     * @author 杨晓慧
     * @Date 2018年12月27日08:39:44
     */
    @Override
    public ItooResult queryQuestionMainByPaperId(String paperId, String courseId, String schoolYear) {
        if (StringUtils.isEmpty(paperId)) {
            log.warn("课程问卷id为空，coursedId{},schoolYear{}",courseId,schoolYear);
            return ItooResult.build(ItooResult.FAIL,"课程id问卷为空！");
        }
        if (StringUtils.isEmpty(courseId)) {
            log.warn("课程问卷id为空，paperId{},schoolYear{}",paperId,schoolYear);
            return ItooResult.build(ItooResult.FAIL,"课程id为空！");
        }
        if (StringUtils.isEmpty(schoolYear)) {
            log.warn("学年学期为空，paperId{},courseId{}",paperId,courseId);
            return ItooResult.build(ItooResult.FAIL,"问卷学年学期为空！");
        }
        final List<AssessmentAdviceModel> assessmentAdviceModels = assessmentAdviceDao.queryQuestionMainByPaperId(paperId, courseId, schoolYear);
        if (CollectionUtils.isEmpty(assessmentAdviceModels)) {
            return ItooResult.build(ItooResult.FAIL,"查询课程问卷简答题题干结果为空！");
        }else{
            return ItooResult.build(ItooResult.SUCCESS, "查询文件简答题题干成功!", assessmentAdviceModels);
        }
    }

    /**
     * 实时更新评教建议到数据库和redis
     * @param model
     * @return boolean
     * @author 魏恩君
     * @since 2.0.0 2019/3/21
     */

    @Override
    public Boolean updateAdviceRecord(EvaluationRecordModel model){
        Boolean flag = true;

        // 1.先查询redis的答题记录
        String keyName = QUESTIONNAIRE_REDIS_INFO + ":" + model.getCourseId() + ":" + model.getPaperId() + ":" + model.getStudentId();
        QuestionNaireAllInfoModel questionNaireAllInfoModel = (QuestionNaireAllInfoModel) redisTemplate.opsForValue().get(keyName);

        // 2.判断redis里是否有记录,如果有记录,则直接更新表和redis
        if(questionNaireAllInfoModel != null || !ObjectUtils.isEmpty(questionNaireAllInfoModel)){
            // 先更新评教建议表
            if("".equals(model.getRecordId())){
                flag = assessmentAdviceDao.updateAdviceRecord(model);
            }else{
                flag = assessmentAdviceDao.updateAdviceRecordById(model);
            }

            if(flag == false){
                log.error("更新评教建议表失败,paperId为{},courseId为{},studentId为{},题干id为{}",model.getPaperId(),model.getCourseId(),model.getStudentId(),model.getEvaluationMainId());
                return false;
            }

            //2.更新redis
            List<EvaluationPaperDetailModel> detailList = questionNaireAllInfoModel.getTeEvaluationPaperDetailModels();
            //detailList.stream().filter(a -> model.getEvaluationMainId().equals(a.getEvaluationMainId())).collect(Collectors.toList());

            for(EvaluationPaperDetailModel detailModel:detailList){
                if(detailModel.getEvaluationMainId() == model.getEvaluationMainId() || detailModel.getEvaluationMainId().equals(model.getEvaluationMainId())){
                    detailModel.setAdvice(model.getAdvice());
                    detailModel.setDone(true);
                }
            }
            redisTemplate.opsForValue().set(keyName,questionNaireAllInfoModel);
        }
        // 如果redis里没有记录,则直接更新数据库,并且查询所有题和答案更新到redis
        else{
            // 更新表
            if("".equals(model.getRecordId())){
                flag = assessmentAdviceDao.updateAdviceRecord(model);
            }else{
                flag = assessmentAdviceDao.updateAdviceRecordById(model);
            }
            if(flag == false){
                log.error("更新评教建议表失败,paperId为{},courseId为{},studentId为{},题干id为{}",model.getPaperId(),model.getCourseId(),model.getStudentId(),model.getEvaluationMainId());
                return false;
            }

            //从库查询所有的题和答题记录,更新到redis
            QuestionNaireAllInfoModel questionNaireModel = evaluationPaperService.queryNaireAndRecord(model.getPaperId(),model.getCourseId(),model.getStudentId(),model.getSchoolYearId());
            redisTemplate.opsForValue().set(keyName,questionNaireModel,3600*4, TimeUnit.SECONDS);
        }
        return flag;
    }

}
